import { type PaginationProps } from "@pureadmin/table";
import { ElMessage, FormInstance } from "element-plus";
import {
  PurchaseOrdersGetAllByPagedAndSort,
  PurchaseOrdersGetInfoById,
  GetSignedSupplierEnterpriseInfoNames,
  GetDictionaryByDictCode,
  PurchaseOrdersUpdateOrderStatus
} from "@/api/stu/SupplyChainFinance"
import { useRoute } from "vue-router";
import { ref, reactive, nextTick, watch, onMounted, computed } from "vue";
import qs from "qs";
import { FXQ } from "@/utils/public/FXQ"
import { P } from "@antv/g2plot";
export function useEBusinessPurchase() {
  const route = useRoute()
  const Visible = ref(false)
  const orderType = ref()
  const loading = ref<boolean>(false);
  const dataList = ref<any>([]);
  const Visible_formList = ref();
  const RefStubimAddFrom = ref();
  const isSeal = ref<boolean>(false)
  const selectId = ref()
  const pagination = reactive<PaginationProps>({
    total: 0,
    pageSize: 20,
    currentPage: 1,
    pageSizes: [10, 20, 50, 100],
    background: true
  });
  const stubim_form = ref()

  const supplierList = ref()
  const payList = ref()
  const columns = [
    {
      label: "序号",
      type: "index",
      fixed: "left",
      minWidth: 50
    },
    {
      label: "采购项目名称",
      prop: "purchaseName",
    },
    {
      label: "供应商企业名称",
      prop: "supplyName",
    }, {
      label: "采购订单号",
      prop: "orderNumber",
    },
    {
      label: "订购日期",
      prop: "orderDate",
    }, {
      label: "交货日期",
      prop: "deliveryDate",
    },
    {
      label: "交货地址",
      prop: "deliveryAddress",
    },
    {
      label: "订单状态",
      prop: "status",
      cellRenderer: ({ row }) => (
        <el-tag type={
          row.status == "0" ? "warning" :
            row.status == "1" ? "success" :
              "danger"}>
          {
            row.status == "0" ? "未处理" :
              row.status == "1" ? "已接受" :
                "已拒绝"
          }
        </el-tag>
      )
    },
    {
      label: "操作",
      midWidth: 200,
      slot: "operation"
    }
  ];

  async function handleOrder(row) {
    selectId.value = row.purchaseOrderId
    orderType.value = row.status
    const data = qs.stringify({
      id: row.purchaseOrderId
    })
    let res = await PurchaseOrdersGetInfoById(data)
    if (res.success) {
      stubim_form.value = res?.data
      stubim_form.value['defaultInfo'] = '****'
      Visible_formList.value = JSON.parse(res?.data.purchaseDetails)
      let total = 0
      //计算商品总额
      Visible_formList.value.forEach(item => {
        item.total = item.Price * item.Quantity
        total = total + (item.total)
      })
      stubim_form.value['totalMoney'] = total
      Visible.value = true
      nextTick(() => {
        const MYFXQ = FXQ.companySeal('xxxx电商企业公司', 0, 0, '', '');
        let view_FQX = document.querySelector("#view_FQX");
        let MYFQX = `<img src='${MYFXQ}' style="width:100%;height:100%"  />`
        view_FQX.innerHTML = MYFQX;
        if (orderType.value == 1) {
          Signet()
        }
      })
    } else {
      ElMessage.error(res.msg);
    }
    //渲染采购方印章
  }

  // 盖章
  function Signet() {
    // // 生成章
    const supplierName = supplierList.value.filter(item => item.seiId == stubim_form.value['seiId'])[0]?.supplyName
    const MYFXQ = FXQ.companySeal(supplierName, 0, 0, '', '');
    let view_FQX = document.querySelector("#view_FQX1");
    let MYFQX = `<img src='${MYFXQ}' style="width:100%;height:100%"  />`
    view_FQX.innerHTML = MYFQX;
    isSeal.value = true
  }

  function closeVisible() {
    Visible.value = false
    isSeal.value = false
  }

  async function AcceptOrder() {
    if (!isSeal.value) {
      ElMessage.warning('请先盖章')
      return
    }
    const data = qs.stringify({
      id: selectId.value,
      status: 1,
    })
    let res = await PurchaseOrdersUpdateOrderStatus(data)
    if (res.status == 200) {
      ElMessage.success('接受订单成功！');
      closeVisible()
      getClientBaseData()
    } else {
      ElMessage.error(res.msg);
    }
  }

  async function RejectOrder() {
    const data = qs.stringify({
      id: selectId.value,
      status: 2,
    })
    let res = await PurchaseOrdersUpdateOrderStatus(data)
    if (res.status == 200) {
      ElMessage.success('拒绝订单成功');
      closeVisible()
      getClientBaseData()
    } else {
      ElMessage.error(res.msg);
    }
  }
  // 分页获取订单列表
  async function getClientBaseData() {
    const data = {
      taskId: route.query.taskId,
      planId: route.query.planId,
      pageIndex: pagination.currentPage,
      pageCount: pagination.pageSize,
      SEIId: sessionStorage.getItem("seiId"),
    }
    const res = await PurchaseOrdersGetAllByPagedAndSort(data);
    if (res.success) {
      res.data.items.forEach(item => {
        item.orderDate = item.orderDate.substring(0, 10)
        item.deliveryDate = item.deliveryDate.substring(0, 10)
      })
      dataList.value = res.data.items;
      pagination.total = res.data.totalCount
    } else {
      ElMessage.error(res.msg)
    }
  }

  onMounted(async () => {
    getClientBaseData()
    const data1 = {
      taskId: route.query.taskId,
      planId: route.query.planId
    }
    const res2 = await GetSignedSupplierEnterpriseInfoNames(data1)
    if (res2.success) {
      supplierList.value = res2?.data;
    } else {
      ElMessage.success(res2.msg)
    }
    let data = qs.stringify({
      dictCode: 'DuePaymentDate'
    })
    const res4 = await GetDictionaryByDictCode(data)
    if (res4.success) {
      payList.value = res4.data;
    } else {
      ElMessage.success(res4.msg)
    }
  })

  function handleSizeChange() {
    getClientBaseData()
  }
  function handleCurrentChange() {
    getClientBaseData()
  }

  return {
    Visible,
    columns,
    loading,
    dataList,
    pagination,
    handleSizeChange,
    handleCurrentChange,
    stubim_form,
    Visible_formList,
    payList,
    supplierList,
    RefStubimAddFrom,
    Signet,
    isSeal,
    handleOrder,
    closeVisible,
    AcceptOrder,
    RejectOrder,
    orderType,
  }
}
